import axios from 'axios';
import Keycloak from 'keycloak-js';

async function initKeycloak() {
  const keycloak = new Keycloak();
  console.log('set keycloak');
  await keycloak.init({onLoad: 'login-required'});
  return keycloak.token;
}

$(document).ready(async function () {
  var str = window.location.search;
  var parameter = str.split('&');
  var instance_id = parameter[0].substring(4, parameter[0].length);
  var definition_id =  parameter[1].substring(6, parameter[1].length);
  var token = await initKeycloak();
  //console.log(str.substring(4, str.length));
  const data = {"processInstanceId": instance_id};
  
  axios.create({withCredentials: true}).get(
    'http://localhost/camunda/engine-rest/process-definition/'+definition_id+'/diagram', 
    {headers: {'Authorization':'Bearer '+token}}
    ).then(
      res=>{  
        var svgdata = 'data:image/svg+xml;base64,'+window.btoa(unescape(encodeURIComponent(res.data)));
        $('#diagram').prop("src", svgdata);
      }
    )
  axios.create({withCredentials: true}).post(
    'http://localhost/camunda/engine-rest/history/variable-instance', 
    data,
    {headers: {'Content-Type':'application/json', 'Authorization':'Bearer '+token}}
    ).then(
      res=>{
        console.log(res.data[0].processDefinitionId);
        definition_id = res.data[0].processDefinitionId;
        $('#dataTable').DataTable({
          data: res.data,
          columns: [
            {data: "name"},
            {data: "value"},
            {data: "createTime"}
          ]
        });
      }
  )
  axios.create({withCredentials: true}).get(
    'http://localhost/camunda/engine-rest/process-definition/'+definition_id+'/diagram', 
    {headers: {'Content-Type':'application/json', 'Authorization':'Bearer '+token}}
    ).then(
      res=>{
        $()
      }
    )
});
  